package cn.exam.sys.servlets;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;

import com.alibaba.excel.EasyExcel;
import com.mysql.cj.util.StringUtils;

import cn.exam.common.PageControl;
import cn.exam.common.Pager;
import cn.exam.model.Score;
import cn.exam.model.ScoreTemplate;
import cn.exam.sys.services.impl.ScoreService;
import cn.exam.sys.services.interfaces.IScoreService;

public class ScoreServlet extends HttpServlet{
	IScoreService service = new ScoreService();
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String cmd = request.getParameter("cmd");
		if(cmd.equals("list")){
			list(request,response);
		}else if(cmd.equals("export")) {
			this.export(request, response);
		}
	}
	/**
	 * 导出
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws Exception
	 */
	private void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PageControl pc = new PageControl();
		pc.setCurrentindex(1);
		pc.setPagesize(1000);
		Pager<Score> pager = service.list(pc);
		List<Score> scoreList=pager.getList();
		if(CollectionUtils.isNotEmpty(scoreList)) {
			for(Score score:scoreList) {
				Date date=StringUtils.isNullOrEmpty(score.getSpid())?null:new Date(Long.parseLong(score.getSpid()));
				// 创建一个SimpleDateFormat对象，指定格式模式
		        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        // 使用format方法将Date对象转换为字符串
		        score.setSpid(sdf.format(date));
			}
		}
		
		List<ScoreTemplate> list=scoreList.stream().map(s->new ScoreTemplate(s.getPname(),s.getStudentName(),s.getScore(),s.getSpid())).collect(Collectors.toList());
		final String filename=URLEncoder.encode(new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"成绩.xlsx", "UTF-8");
		// 设置响应头为下载文件方式，并指定文件类型和文件名
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename="+filename);
        
        // 使用EasyExcel的write方法写入数据到response的输出流中
        ServletOutputStream out = response.getOutputStream();
        EasyExcel.write(out, ScoreTemplate.class).sheet("成绩").doWrite(list);
        out.flush(); // 刷新输出流，确保数据被发送到客户端
        out.close(); // 关闭输出流
	}
	
	/**
	 * 查询成绩列表
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PageControl pc = new PageControl();
		Integer currindex = 1;
		if(request.getParameter("index")!=null){
			currindex = Integer.parseInt(request.getParameter("index"));
		}
		pc.setCurrentindex(currindex);
		Pager<Score> pager = service.list(pc);
		List<Score> scoreList=pager.getList();
		if(CollectionUtils.isNotEmpty(scoreList)) {
			for(Score score:scoreList) {
				Date date=StringUtils.isNullOrEmpty(score.getSpid())?null:new Date(Long.parseLong(score.getSpid()));
				// 创建一个SimpleDateFormat对象，指定格式模式
		        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        // 使用format方法将Date对象转换为字符串
		        score.setSpid(sdf.format(date));
			}
		}
		
		request.setAttribute("pager", pager);
		request.getRequestDispatcher("/sys/score/list.jsp").forward(request, response);
		
	}
}
